<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="50%"
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <el-tree
      ref="treeRef"
      :data="menuTree"
      show-checkbox
      check-strictly="true"
      node-key="menuId"
      :props="defaultProps"
      :default-checked-keys="checkedKeys"
      default-expand-all
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { getMenus } from "@/api/menu";
import { ElMessage } from "element-plus";
import { getRoleMenus, saveRoleMenus } from "@/api/role";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  roleId: {
    type: [String, Number],
    default: "",
  },
  currentMenus: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const title = "角色菜单权限分配";
const dialogVisible = ref(false);
const menuList = ref([]);
const menuTree = ref([]);
const checkedKeys = ref([]);
const treeRef = ref(null);

const defaultProps = {
  children: "children",
  label: "menuName",
};

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal) {
      initData();
    }
  }
);

// 监听dialogVisible变化
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit("update:modelValue", newVal);
  }
);

// 初始化数据
const initData = async () => {
  try {
    // 获取所有菜单
    const menuResponse = await getMenus();
    menuList.value = menuResponse.data.data || [];

    // 从顶层(parentId=1)开始构建树
    menuTree.value = buildMenuTree(1);

    // 获取角色当前的菜单权限
    if (props.roleId) {
      const roleMenuResponse = await getRoleMenus(props.roleId);

      // 确保将数字转换为字符串
      if (roleMenuResponse && roleMenuResponse.data) {
        checkedKeys.value = roleMenuResponse.data.map((id) => String(id));
      } else {
        checkedKeys.value = [];
      }
    }
  } catch (error) {
    ElMessage.error("初始化数据失败");
    checkedKeys.value = [];
  }
};

// 构建树形结构
const buildMenuTree = (parentId) => {
  return menuList.value
    .filter((item) => item.menuParentId === parentId)
    .map((item) => ({
      ...item,
      children: buildMenuTree(item.menuId),
    }));
};

// 确认按钮
const handleConfirm = async () => {
  if (!treeRef.value || !props.roleId) return;

  const checkedNodes = treeRef.value.getCheckedNodes();
  const halfCheckedNodes = treeRef.value.getHalfCheckedNodes();
  const selectedMenus = [...checkedNodes, ...halfCheckedNodes].map(
    // 确保发送到后端的是数字类型
    (node) => Number(node.menuId)
  );

  try {
    await saveRoleMenus(props.roleId, selectedMenus);
    ElMessage.success("保存成功");
    emit("success");
    handleClose();
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  checkedKeys.value = [];
};
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}
</style>
